package net.godbirds.boot.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * json与对象转换工具类
 * @author CZH
 */
public class JsonUtil {

	/**
	 * json转实体对象
	 * @param jsonName
	 * @param tClass
	 * @return
	 */
	public static <T> T json2Obj(String jsonName, Class<T> tClass) {
		try {
			InputStream jsonInStream = JsonUtil.class.getClassLoader().getResourceAsStream(jsonName);
			String jsonStr = convertStream2Json(jsonInStream);
			return JSON.parseObject(jsonStr, tClass);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * json转集合对象
	 * @param jsonName
	 * @param tClass
	 * @return
	 */
	public static <T> List<T> json2List(String jsonName, Class<T> tClass) {
		try {
			InputStream jsonInStream = JsonUtil.class.getClassLoader().getResourceAsStream(jsonName);
			String jsonStr = convertStream2Json(jsonInStream);
			return JSON.parseArray(jsonStr, tClass);
		} catch (Exception e) {
			return null;
		}
	}

	public static String convertStream2Json(InputStream inputStream) {
		String jsonStr = "";
		// ByteArrayOutputStream相当于内存输出流
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		// 将输入流转移到内存输出流中
		try {
			while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
				out.write(buffer, 0, len);
			}
			// 将内存流转换为字符串
			jsonStr = new String(out.toByteArray(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonStr;
	}
	/**
	 * 集合List转成JSON字符串
	 * @param list
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String conver2Json(List list){
		return JSON.toJSON(list).toString();
	}
	/**
	 * 集合对象等转换成JSON字符串
	 * @param obj
	 * @return
	 */
	public static String conver2Json(Object obj){
		return JSON.toJSON(obj).toString();
	}
	/**
	 * 实例化XML格式字符串成JSON格式字符串
	 * @param xml
	 * @return
	 */
	public static String xml2Json(String xml){
		JSONObject obj = new JSONObject();
		try {
			InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			SAXBuilder sb = new  SAXBuilder();
			Document doc = sb.build(is);
			Element root = doc.getRootElement();
			obj.put(root.getName(), iterateElement(root));
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 实例化指定XML格式的文件成JSON格式字符串
	 * @param file
	 * @return
	 */
	public static String xml2Json(File file){
		JSONObject obj = new JSONObject();
		try {
			SAXBuilder sb = new  SAXBuilder();
			Document doc = sb.build(file);
			Element root = doc.getRootElement();
			obj.put(root.getName(), iterateElement(root));
			return obj.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 迭代遍历元素，转换成Map集合
	 * @param root
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map iterateElement(Element root){
		List node = root.getChildren();
		Element et = null;
		Map obj = new HashMap();
		List list = null;
		for(int i = 0; i < node.size(); i++){
			list = new LinkedList();
			et = (Element) node.get(i);
			if(et.getTextTrim().equals("")){
				if(et.getChildren() == null || et.getChildren().size() == 0){
					continue;
				}
				if(obj.containsKey(et.getName())){
					list = (List)obj.get(et.getName());
				}
				list.add(iterateElement(et));
				obj.put(et.getName(),list);
			}else{
				if(obj.containsKey(et.getName())){
					list = (List) obj.get(et.getName());
				}
				list.add(et.getTextTrim());
				obj.put(et.getName(), list);
			}
		}
		return obj;
	}
}
